package ua.org.nuos.sdms.middle.dao;

import org.apache.commons.lang.Validate;
import ua.org.nuos.sdms.middle.entity.User;
import ua.org.nuos.sdms.middle.util.EntityValidator;
import ua.org.nuos.sdms.middle.util.validator.UserValidator;

import javax.annotation.PostConstruct;
import javax.ejb.Local;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

/**
 * Created by IntelliJ IDEA.
 * User: dio
 * Date: 09.10.11
 * Time: 21:06
 * To change this template use File | Settings | File Templates.
 */
@LocalBean
@Stateless
public class UserDaoBean {

    private static Logger logger = Logger.getLogger(UserDaoBean.class.getSimpleName());

    @PersistenceContext(unitName = "persistence")
    protected EntityManager em;

    private UserValidator validator;

    @PostConstruct
    protected void init() {
        validator = new UserValidator(em);
    }

    /**
     * Create new user
     *
     * @param user user
     *             User.email is required
     *             User.password is required
     */
    public void createUser(User user) {
        validator.validate(user);
        em.persist(user);
    }

    /**
     * Update existing user
     *
     * @param user user
     *             User.id is required
     */
    public void update(User user) {
        validator.validatePersisted(user);
        em.merge(user);
    }

    /**
     * Find existing user by user email
     *
     * @param userId user id
     * @return user
     */
    public User findById(long userId) {
        Validate.isTrue(userId > 0);

        return em.find(User.class, userId);
    }

    /**
     *
     * @param email
     * @return user can be null
     */
    public User findByEmail(String email) {
        Validate.notEmpty(email);

        try {
            return em.createNamedQuery(User.QUERY_FIND_BY_EMAIL, User.class).setParameter("email", email).getSingleResult();
        } catch (NoResultException e) {
            return null;
        }
    }

    /**
     *
     * @param name
     * @return user can be null
     */
    public List<User> findByName(String name) {
        Validate.notEmpty(name);

        try {
            return em.createNamedQuery(User.QUERY_FIND_BY_NAME, User.class).setParameter("name", name).getResultList();
        } catch (NoResultException e) {
            return new ArrayList<User>();
        }
    }

    /**
     * Remove existing user
     *
     * @param userId user email
     */
    public void remove(long userId) {
        Validate.isTrue(userId > 0);

        User user = em.find(User.class, userId);
        EntityValidator.checkExisting(user, userId);

        em.remove(user);
    }

}
